window.setInterval("getMessages()", 3000);

var xmlHttpRequest = null;
var currentMessageNumber = 0;

sendMessage = function()
{
	var username, message;
	
	username = document.getElementById("username").value;
	message = document.getElementById("message").value;

	if (username != "" && message != "")
	{
		var url = "./Chat";
		var data = "username=" + username + "&message=" + message + "&timestamp=" + new Date().getTime();;
		document.getElementById("message").value = "";
		
		xmlHttpRequest = newXmlHttpRequest();
		xmlHttpRequest.onreadystatechange = null;
		xmlHttpRequest.open("POST", url, true);
		xmlHttpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlHttpRequest.setRequestHeader("Content-length", data.length);
		xmlHttpRequest.setRequestHeader("Connection", "close");
		xmlHttpRequest.send(data);
	}
	else
		alert("Bitte Username und Nachricht eingeben!");
}

getMessages = function()
{
	var url = "./Chat?currentMessageNumber=" + currentMessageNumber + "&timestamp=" + new Date().getTime();
	
	xmlHttpRequest = newXmlHttpRequest();
	xmlHttpRequest.onreadystatechange = printMessages;
	xmlHttpRequest.open("GET", url, true);
	xmlHttpRequest.send(null);
}

printMessages = function()
{
	if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200)
	{
		var xmlDocument = xmlHttpRequest.responseXML.documentElement;
		var messageCount = xmlDocument.getElementsByTagName('message').length;
		
		if (messageCount > 0)
		{
			for (var i = 0; i < messageCount; i++)
				document.getElementById("messages").innerHTML += "<i>(" 
					+ xmlDocument.getElementsByTagName('message')[i].getElementsByTagName("time")[0].firstChild.nodeValue + ")</i> <b>"
					+ xmlDocument.getElementsByTagName('message')[i].getElementsByTagName("username")[0].firstChild.nodeValue + "</b>: "
					+ xmlDocument.getElementsByTagName('message')[i].getElementsByTagName("text")[0].firstChild.nodeValue + "<br>";
			
			currentMessageNumber = xmlDocument.getElementsByTagName("messageCountGlobal")[0].firstChild.nodeValue;
			
			scrollDown();
		}
	}
}

newXmlHttpRequest = function()
{
	var xmlHttpReq;
	
	try
	{
		xmlHttpReq = new XMLHttpRequest();
	}
	catch (exception1)
	{
		try
		{
			xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (exception2)
		{
			xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	
	return xmlHttpReq;
}

scrollDown = function()
{
	var messagesDiv = document.getElementById("messages");
	messagesDiv.scrollTop = messagesDiv.scrollHeight;
} 